#!/bin/sh
set -e
set -u

TMPDIR=$(mktemp -d)
PROFILES="initramfs kernel iso installer nocloud metal"
FIRMWARES="amd-ucode amdgpu bnx2-bnx2x i915 intel-ice-firmware intel-ucode qlogic-firmware"
EXTENSIONS="drbd zfs"

mkdir -p images/talos/profiles

printf "fetching talos version: "
talos_version=${1:-$(skopeo --override-os linux --override-arch amd64 list-tags docker://ghcr.io/siderolabs/imager | jq -r '.Tags[]' | grep '^v[0-9]\+.[0-9]\+.[0-9]\+$' | sort -V | tail -n 1)}
echo "$talos_version"

export "TALOS_VERSION=$talos_version"

crane export ghcr.io/siderolabs/extensions:${TALOS_VERSION} | tar x -O image-digests > $TMPDIR/image-digests

for firmware in $FIRMWARES; do
  printf "fetching %s version: " "$firmware"
  firmware_var=$(echo "$firmware" | tr '[:lower:]' '[:upper:]' | tr - _)_IMAGE
  image=$(grep -F "/$firmware:" $TMPDIR/image-digests)
  echo "$image"
  export "$firmware_var=$image"
done

for extension in $EXTENSIONS; do
  printf "fetching %s version: " "$extension"
  extension_var=$(echo "$extension" | tr '[:lower:]' '[:upper:]' | tr - _)_IMAGE
  image=$(grep -F "/$extension:" $TMPDIR/image-digests)
  echo "$image"
  export "$extension_var=$image"
done

for profile in $PROFILES; do
  echo "writing profile images/talos/profiles/$profile.yaml"
  case "$profile" in
    initramfs|kernel|iso)
      image_options="{}"
      out_format="raw"
      platform="metal"
      kind="$profile"
      ;;
    installer)
      image_options="{}"
      out_format="raw"
      platform="metal"
      kind="installer"
      ;;
    metal)
      image_options="{ diskSize: 1306525696, diskFormat: raw }"
      out_format=".xz"
      platform="metal"
      kind="image"
      ;;
    nocloud)
      image_options="{ diskSize: 1306525696, diskFormat: raw }"
      out_format=".xz"
      platform="nocloud"
      kind="image"
      ;;
    *)
      echo "Unknown profile: $profile" >&2
      exit 1
      ;;
  esac

  cat > images/talos/profiles/$profile.yaml <<EOT
# this file generated by hack/gen-profiles.sh
# do not edit it
arch: amd64
platform: ${platform}
secureboot: false
version: ${TALOS_VERSION}
input:
  kernel:
    path: /usr/install/amd64/vmlinuz
  initramfs:
    path: /usr/install/amd64/initramfs.xz
  baseInstaller:
    imageRef: "ghcr.io/siderolabs/installer:${TALOS_VERSION}"
  systemExtensions:
    - imageRef: ${AMD_UCODE_IMAGE}
    - imageRef: ${AMDGPU_IMAGE}
    - imageRef: ${BNX2_BNX2X_IMAGE}
    - imageRef: ${INTEL_ICE_FIRMWARE_IMAGE}
    - imageRef: ${I915_IMAGE}
    - imageRef: ${INTEL_UCODE_IMAGE}
    - imageRef: ${QLOGIC_FIRMWARE_IMAGE}
    - imageRef: ${DRBD_IMAGE}
    - imageRef: ${ZFS_IMAGE}
output:
  kind: ${kind}
  imageOptions: ${image_options}
  outFormat: ${out_format}
EOT
done
